<template>
  <div class="class-courses-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="header-title">班级课程管理 - {{ classInfo.className }}</span>
      </template>
    </el-page-header>
    
    <el-card class="courses-card">
      <div class="action-bar">
        <el-button 
          type="primary" 
          @click="showAddCourseDialog"
          :icon="Plus"
        >
          添加课程
        </el-button>
      </div>
      
      <el-table :data="courses" border style="width: 100%" v-loading="loading">
        <el-table-column prop="courseName" label="课程名称" width="180" />
        <el-table-column prop="teacherName" label="授课教师" width="120" />
        <el-table-column prop="studentCount" label="学生人数" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="removeCourse(row.id)"
              :icon="Delete"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加课程对话框 -->
    <el-dialog 
      v-model="showCourseDialog" 
      title="添加课程到班级" 
      width="40%"
      :close-on-click-modal="false"
    >
      <div class="course-select-dialog">
        <el-select 
          v-model="selectedCourseId" 
          placeholder="请选择课程" 
          filterable
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="course in availableCourses"
            :key="course.id"
            :label="course.name"
            :value="course.id"
          />
        </el-select>
        
        <div class="dialog-footer" style="margin-top: 20px; text-align: right">
          <el-button @click="showCourseDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmAddCourse"
            :disabled="!selectedCourseId"
            :loading="loading"
          >
            确认添加
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { classApi } from '@/api/class'
import { teacherApi } from '@/api/teacher'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const classInfo = ref({})
const courses = ref([])
const showCourseDialog = ref(false)
const selectedCourseId = ref(null)
const availableCourses = ref([])

const formatDate = (dateString) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm') : '未知时间'
}

const loadClassInfo = async () => {
  try {
    const response = await classApi.getClassInfo(route.params.id)
    classInfo.value = response
  } catch (error) {
    console.error('加载班级信息失败:', error)
    ElMessage.error('加载班级信息失败')
  }
}

const loadCourses = async () => {
  try {
    loading.value = true
    const response = await classApi.getClassCourses(route.params.id)
    courses.value = response.data || response
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  } finally {
    loading.value = false
  }
}

const loadAvailableCourses = async () => {
  try {
    const teacherId = await teacherApi.getTeacherByUid(/* 获取教师ID */)
    const response = await teacherApi.getTeacherCourses(teacherId)
    availableCourses.value = response.map(course => ({
      id: course.id,
      name: course.couName || course.name
    }))
  } catch (error) {
    console.error('加载可选课程失败:', error)
    ElMessage.error('加载可选课程失败')
  }
}

const showAddCourseDialog = async () => {
  await loadAvailableCourses()
  showCourseDialog.value = true
}

const confirmAddCourse = async () => {
  if (!selectedCourseId.value) {
    ElMessage.warning('请选择要添加的课程')
    return
  }

  try {
    loading.value = true
    await classApi.addCourseToClass(route.params.id, selectedCourseId.value)
    ElMessage.success('课程添加成功')
    showCourseDialog.value = false
    selectedCourseId.value = null
    await loadCourses()
  } catch (error) {
    console.error('添加课程失败:', error)
    ElMessage.error(error.response?.data?.message || '添加课程失败')
  } finally {
    loading.value = false
  }
}

const removeCourse = async (courseId) => {
  try {
    await ElMessageBox.confirm('确定要移除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    await classApi.removeCourseFromClass(route.params.id, courseId)
    ElMessage.success('课程移除成功')
    await loadCourses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除课程失败:', error)
      ElMessage.error('移除课程失败')
    }
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.go(-1)
}

onMounted(async () => {
  await Promise.all([loadClassInfo(), loadCourses()])
})
</script>

<style scoped>
.class-courses-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.action-bar {
  margin-bottom: 20px;
}

.courses-card {
  margin-top: 20px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>